﻿<template>
  <div class="app-container">
    <div class="chart-title with-back">
      <div class="chart-left">
        <div>终端采购单</div>
        <div class="backtrack">
          <el-button @click="comeBack">返回</el-button>
        </div>
      </div>
    </div>
    <div class="goods-condition">
      <div class="search-items">
        <div class="search-title">供货商信息</div>
        <div class="search-content">
          <el-form :inline="true"
                   :model="temp"
                   class="demo-form-inline">
            <el-form-item :label="$t('public.circle') + ':'">
              <el-checkbox v-for="(items, index) in circleOptions"
                           :key="index"
                           :checked="indexOf(items, checkedCircle)"
                           @change="
                change(items, indexOf(items, checkedCircle), 'checkedCircle')
              ">
                {{ items.name }}</el-checkbox>
            </el-form-item>
            <el-form-item :label="$t('terminal.type') + ':'">
              <el-cascader v-model="temp.category_id"
                           :options="terminalOptions"
                           :props="optionProps"
                           multiple="false"
                           @change="changeEquipment()"
                           clearable
                           :show-all-levels="false"></el-cascader>
            </el-form-item>

            <el-form-item v-if="equipmentOptions.length>0"
                          :label="$t('terminal.name') + ':'">
              <el-checkbox v-for="(items, index) in equipmentOptions"
                           :key="index"
                           :checked="indexOf(items, checkedEquipment)"
                           @change="
                change(
                  items,
                  indexOf(items, checkedEquipment),
                  'checkedEquipment'
                )
              ">
                {{ items.name }}</el-checkbox>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="table-banner"></div>
      <div class="search-table">
        <el-table :data="goodsOptions"
                  border
                  fit
                  highlight-current-row
                  :header-cell-style="{'background-color':'#F2F2F4','color': '#8B94BE'}"
                  style="width: 100%">
          <el-table-column fixed
                           align="center"
                           :label="$t('goods.name')">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           :label="$t('goods.code_2')">
            <template slot-scope="scope">
              <span>{{ scope.row.code }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           :label="$t('public.brand')">
            <template slot-scope="scope">
              <span>{{ scope.row.brand_name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           :label="$t('goods.attribute')">
            <template slot-scope="scope">
              <span>{{ scope.row.attribute }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           :label="$t('public.units')">
            <template slot-scope="scope">
              <span>{{ scope.row.units_name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           :label="$t('goods.oldPrice')">
            <template slot-scope="scope">
              <span>{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           :label="$t('goods.newPrice')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.new_price"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="table-banner"></div>
      <div class="submit-items">
        <el-form ref="form"
                 :model="temp"
                 label-width="80px">

          <el-form-item :label="$t('application.type') + ':'">
            <el-radio-group v-model="temp.type">
              <el-radio :label="1">立即生效</el-radio>
              <el-radio :label="2">区间调价</el-radio>
              <el-radio :label="3">设定时间</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('application.reason') + ':'">
            <el-input type="textarea"
                      :autosize="{ minRows: 2, maxRows: 6 }"
                      placeholder="请输入内容"
                      v-model="temp.adjust_reason"></el-input>
          </el-form-item>
        </el-form>
        <div class="stock-footer">
          <div></div>
          <div class="operat-form">
            <button @click="handleCreate"
                    class="adopt">立即创建</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
export default {
  name: "PurchaseRequisition",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    return {
      chartData: undefined,
      dialogVisible: false,
      dialogChartFormVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        name: [{ required: true, message: "请选择商品", trigger: "change" }]
      },
      index: undefined,
      index_2: undefined,
      warehouseOptions: [],
      warehouseCount: undefined,
      inStockOption: [],
      temp: {
        merchant_circle_ids: undefined,
        merchant_circle_name: "",
        list: [],
        type: 1,
        adjust_reason: ""
      },
      program: {
        id: undefined,
        name: "",
        amount: ""
      },
      circleOptions: [],
      checkedCircle: [],
      result: [],
      terminalOptions: [],
      equipmentOptions: [],
      checkedEquipment: [],
      checkedGoods: [],
      goodsOptions: [],
      goodsCount: undefined,
      pageSize: 20,
      optionProps: {
        value: 'id',
        label: 'name'
      }
    };
  },
  created() {
    this.getBusinessDistrict();
    this.getTerminalType();
  },
  methods: {
    getList() {
      this.listLoading = true;
      const data = {
        ids: this.ids ? this.ids : ""
      };
      const path = {
        app: "goods",
        api: "api_goods_index_createPurchaseRequest",
        version: "1.0",
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    comeBack() {
      this.$router.push("/price-data/adjust-price-application-list");
    },
    handleCreate() {
      // 检测是否改价
      const list = [];
      if (this.goodsOptions.length > 0) {
        const goodsOptions = this.goodsOptions;
        goodsOptions.forEach(element => {
          if (element.new_price) {
            list.push({
              id: element.id,
              new_price: parseInt(element.new_price)
            });
          }
        });
      }
      if (list.length === 0) {
        this.$message.error("至少调价一个商品");
        return false;
      }

      // 商圈
      let merchant_circle_ids = "";
      let merchant_circle_name = "";
      if (this.checkedCircle.length > 0) {
        const circle = this.checkedCircle;
        merchant_circle_ids = circle
          .map(circle => circle.id)
          .join(",");
        merchant_circle_name = circle
          .map(circle => circle.name)
          .join(",");
      }
      // 分类
      let category_id = "";
      let category_name = "";
      if (this.temp.category_id && this.temp.category_id.length > 0) {
        category_id = this.temp.category_id.slice(-1).join(',')
        const data = this.terminalOptions;
        data.forEach(element => {
          element.children.forEach(res => {
            if (parseInt(category_id) === res.id) {
              category_name = res.name;
            }
          })
        });
      }

      // 设备
      let equipment_ids = "";
      let equipment_code = "";
      let equipment_count = 0;
      if (this.checkedEquipment.length > 0) {
        const equipment = this.checkedEquipment;
        equipment_ids = equipment
          .map(equipment => equipment.id)
          .join(",");
        equipment_code = equipment
          .map(equipment => equipment.code)
          .join(",");
        equipment_count = equipment.length;
      }

      this.temp.goods_count = this.temp.list.length;

      const path = {
        app: "equipment",
        api: "api_equipment_goods_adjustPriceAdd",
        version: "1.0",
        data: {
          merchant_circle_ids: merchant_circle_ids,
          merchant_circle_name: merchant_circle_name,
          category_id: category_id,
          category_name: category_name,
          equipment_ids: equipment_ids,
          equipment_code: equipment_code,
          equipment_count: equipment_count,
          goods_count: 2,
          type: 1,
          list: list
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 商品选择
    getGoods() {
      const officers = this.checkedEquipment;
      if (this.checkedEquipment.length > 0) {
        const path = {
          app: "equipment",
          api: "api_equipment_index_equipmentGoodsList",
          version: "1.0",
          data: {
            equipment_id: officers.map(officer => officer.id).join(","),
            type: 1
          }
        };
        this.socketApi.sendSock(JSON.stringify(path), res => {
          if (res) {
            this.socketData(res);
          }
        });
      } else {
        this.goodsOptions = [];
      }
    },
    choose(data, name) {
      if (name === "goods") {
        this.program.id = data.id;
        this.program.name = data.name;
        this.program.code = data.code;
        this.program.category_name_2 = data.category_name_2;
        this.program.brand_name = data.brand_name;
        this.program.attribute = data.attribute;
        this.program.units_name = data.units_name;
      }
    },
    remove(data, name) {
      if (name === "goods") {
        this.program.id = undefined;
        this.program.name = "";
        this.program.code = "";
        this.program.category_name_2 = "";
        this.program.brand_name = "";
        this.program.attribute = "";
        this.program.units_name = "";
      }
    },
    resetProgram() {
      this.program = {
        id: undefined,
        name: "",
        code: "",
        category_name_2: "",
        brand_name: "",
        attribute: "",
        units_name: "",
        amount: 1
      };
    },
    getBusinessDistrict() {
      const path = {
        app: "archives",
        api: "api_archives_merchantCircle_getList",
        version: "1.0",
        data: {}
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    getTerminalType() {
      const path = {
        app: "archives",
        api: "api_archives_category_getList",
        version: "1.0",
        data: {
          type: 2
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    getTerminal() {
      const officers = this.checkedCircle
      let merchant_circle_id = [];
      if (officers.length > 0) {
        merchant_circle_id = officers.map(function(officer) {
          return officer.id
        });
      }
      const path = {
        app: "archives",
        api: "api_equipment_index_getList",
        version: "1.0",
        data: {
          merchant_circle_id: merchant_circle_id.join(','),
          category_id: this.temp.category_id.length > 0 ? this.temp.category_id.slice(-1).join(',') : ""
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    indexOf(item, items) {
      items = JSON.stringify(items);
      item = JSON.stringify(item);
      if (items.indexOf(item) > -1) {
        return true;
      } else {
        return false;
      }
    },
    change(e, c, name) {
      if (c) {
        this[name].forEach((value, index, array) => {
          if (e.id === value.id) {
            this[name].splice(index, 1);
          }
        });
      } else {
        this[name].push(e);
      }
      this.changeEquipment();
      if (name === "checkedEquipment") {
        this.getGoods();
      }
    },
    changeEquipment() {
      if (this.temp.category_id && this.temp.category_id.length > 0 && this.checkedCircle.length > 0) {
        this.getTerminal()
      } else {
        this.equipmentOptions = [];
        this.checkedEquipment = [];
        this.goodsOptions = [];
      }
    },
    handleChange() { },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_archives_merchantCircle_getList") {
            this.circleOptions = resj.data;
          } else if (resj.api === "api_archives_category_getList") {
            this.terminalOptions = resj.data;
          } else if (resj.api === "api_equipment_index_getList") {
            this.equipmentOptions = resj.data;
            if (!(resj.data.length > 0)) {
              this.checkedEquipment = [];
              this.goodsOptions = [];
            }
          } else if (resj.api === "api_equipment_index_equipmentGoodsList") {
            console.log('resj.data', resj.data)
            const data = resj.data;
            const dataList = [];
            data.forEach(element => {
              if (element.id) {
                element.new_price = "";
                dataList.push(element);
              }
            });
            this.goodsOptions = dataList;
          } else if (resj.api === "api_equipment_goods_adjustPriceAdd") {
            this.$notify({
              title: "成功",
              message: "提交成功",
              type: "success",
              duration: 2000
            });
            this.comeBack()
          }
        }
      }
    }
  }
};
</script>
<style scoped>
.warehouse-info {
  display: flex;
  padding: 14px;
}
.action-bar {
  display: flex;
  justify-content: space-between;
  padding: 14px;
}
.warehouse-info div {
  flex: 1;
}
.action-right {
  display: flex;
}
.action-right div:not(:first-child) {
  margin-left: 14px;
}
</style>
